package com.zwcl.common.web.handler;

//@Service
//public class CustomUrlBlockHandler implements UrlBlockHandler {
//    @Override
//    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
//        httpServletResponse.setHeader("Content-Type","application/json;charset=UTF-8");
//        String message = "{\"code\":5300,\"success\":false,\"message\":\"访问人数过多\",\"data\":null}";
//        //如果加了转义符号看不明白
//        //使用类创建就json对象
//        httpServletResponse.getWriter().write(message);
//    }
//}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.enums.ExceptionCode;
import org.springframework.stereotype.Component;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 自定义sentinel异常返回信息
 */
@Component
public class CustomUrlBlockHandler  implements BlockExceptionHandler{

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
        String msg = null;
        if (ex instanceof FlowException) {
            msg = "限流了";
        } else if (ex instanceof DegradeException) {
            msg = "降级了";
        } else if (ex instanceof ParamFlowException) {
            msg = "热点参数限流";
        } else if (ex instanceof SystemBlockException) {
            msg = "系统规则（负载/...不满足要求）";
        } else if (ex instanceof AuthorityException) {
            msg = "授权规则不通过";
        }
        // http状态码
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        // spring mvc自带的json操作工具，叫jackson
        new ObjectMapper().writeValue(response.getWriter(),
                ApiResult.fail(ExceptionCode.REQUEST_DEGRADE_LIMITER.getCode(),msg));
    }
}


